package com.auto.learning.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.PlayChangeEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.NowPlayEvent;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.tools.FastBlur;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.RoundImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 播放锁屏界面
 *
 */
public class SrceenLockActivity extends SwipeBackActivity {

	private final static int UPDATE_PLAY_TIME = 1;
	private PhoneStatRec phoneStateRec;
	private ImageLoader imageLoader = null;
	private DisplayImageOptions options;
	
	private ImageView image_render,image_play_last,image_play_next,image_play;
	private View text;
	private RelativeLayout rel_main;
	private RoundImageView image_face;
	private SeekBar my_seekbar;
	private TextView tv_current_time,tv_total_time,tv_bookname,tv_sol;
	private boolean isPlaying = true;
	BookBean bookBean = new BookBean();
	private boolean isBackGround = false;
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case UPDATE_PLAY_TIME:
					NowPlayEvent nowPlayBean = (NowPlayEvent)msg.obj;
					if (isPlaying) {
						tv_current_time.setText(nowPlayBean.getCurrentPosition());
						tv_total_time.setText(nowPlayBean.getTotalDuration());
						my_seekbar.setEnabled(true);
						my_seekbar.setMax(nowPlayBean.getTotal());
						my_seekbar.setProgress(nowPlayBean.getCurrent());
					}
					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		setRequestedOrientation(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_screenlock);
		initImageLoader();
		initView();
		phoneStateRec = new PhoneStatRec();// 来电的广播
		IntentFilter mIntentFilter = new IntentFilter();
		mIntentFilter.addAction("android.intent.action.PHONE_STATE");
		registerReceiver(phoneStateRec, mIntentFilter);
		registerEvent();
		TemporaryVariable.activity = this;
	}
	
	
	private void  initView(){
		Intent intent = getIntent();
		bookBean = (BookBean) intent.getSerializableExtra("lock_bookbean_info");
		isBackGround = intent.getBooleanExtra("isBackGround", false);
		image_play_last = (ImageView) findViewById(R.id.image_play_last);
		image_play_next = (ImageView) findViewById(R.id.image_play_next);
		image_play = (ImageView) findViewById(R.id.image_play);
		image_face = (RoundImageView) findViewById(R.id.image_face);
		my_seekbar = (SeekBar) findViewById(R.id.my_seekbar);
		tv_current_time = (TextView) findViewById(R.id.tv_current_time);
		tv_total_time = (TextView) findViewById(R.id.tv_total_time);
		tv_bookname = (TextView) findViewById(R.id.tv_bookname);
		tv_sol = (TextView) findViewById(R.id.tv_sol);
		image_render = (ImageView) findViewById(R.id.image_render);
		text = findViewById(R.id.text);
		rel_main = (RelativeLayout) findViewById(R.id.rel_main);
		rel_main.getBackground().setAlpha(127);
		
		if (bookBean != null) {
			tv_bookname.setText(bookBean.getBookName()+"");
			tv_sol.setText(bookBean.getSlogan()+"");
			ImageLoader.getInstance().displayImage(bookBean.getFaceImg(), image_render);
			ImageLoader.getInstance().displayImage(bookBean.getFaceImgPlay(), image_face, options);
			image_play.setImageResource(R.drawable.playing_big);
		}
		
		image_play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MusicPlayManager.getInstance(SrceenLockActivity.this).pause();
			}
		});
		image_play_last.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				MusicPlayManager.getInstance(SrceenLockActivity.this).previous();
			}
		});
		image_play_next.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				MusicPlayManager.getInstance(SrceenLockActivity.this).next();
			}
		});
		
		my_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				if (fromUser == true) {
					seekBar.setProgress(progress);
					EventBus.getEventBus("m_fase").post(progress);
				}
			}
		});
		
		applyBlur();
	}
	
	@Subscribe
	public void onEventPlayTime(NowPlayEvent nowPlayBean) {
		handler.obtainMessage(UPDATE_PLAY_TIME, nowPlayBean).sendToTarget();
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		this.isPlaying = isPlaying;
		if (isPlaying) {
			image_play.setImageResource(R.drawable.playing_big);
		}else {
			image_play.setImageResource(R.drawable.play_big);
		}
	}
	
	@Subscribe
	public void onEventPlayBeanChange(PlayChangeEvent event){
		MusicPlayManager manager = MusicPlayManager.getInstance(this);
		BookBean m_BookBean = manager.getCurrentPlayingBookBean();
		if (m_BookBean != null) {
			bookBean = m_BookBean;
			tv_bookname.setText(m_BookBean.getBookName()+"");
			tv_sol.setText(m_BookBean.getSlogan()+"");
			ImageLoader.getInstance().displayImage(m_BookBean.getFaceImg(), image_render);
			ImageLoader.getInstance().displayImage(m_BookBean.getFaceImgPlay(), image_face, options);
			if (isPlaying) {
				image_play.setImageResource(R.drawable.playing_big);
			}else {
				image_play.setImageResource(R.drawable.play_big);
			}
		}
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_now_play_time" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_play_bookbean_change", ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_now_play_time" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_play_bookbean_change", ThreadEnforcer.MAIN).unregister(this);
	}
	
	private int time = HttpRequestHelper.BLUR_DEFAULT_TIMES;
	/***
	 * 处理高斯模糊
	 */
	public void applyBlur() {
		image_render.getViewTreeObserver().addOnPreDrawListener(
				new ViewTreeObserver.OnPreDrawListener() {
					@Override
					public boolean onPreDraw() {
						if (time > 0) {
							time --;
						}else {
							image_render.getViewTreeObserver().removeOnPreDrawListener(this);
						}
						image_render.buildDrawingCache();
						Bitmap bmp = image_render.getDrawingCache();
						FastBlur.blur(bmp, text, SrceenLockActivity.this);
						return true;
				}
		});
	}

	/**
	 * 初始化IMAGELOADER
	 */
	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_512)
				.showImageForEmptyUri(R.drawable.default_512)
				.showImageOnFail(R.drawable.default_512).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}



	
	/**
	 * 界面销毁的安全退出界面机制
	 */
	@Override
	protected void onDestroy() {
		TemporaryVariable.activity = null;
		/**
		 * 触发home键按钮
		 */
		if (isBackGround) {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);           
			startActivity(intent);
		}
		
		if (phoneStateRec != null) {
			unregisterReceiver(phoneStateRec);
		}
		unRegisterEvent();
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 处理来电的时候的暂停
	public class PhoneStatRec extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			TelephonyManager mTelManager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			switch (mTelManager.getCallState()) {
			case TelephonyManager.CALL_STATE_OFFHOOK:// 通话
				SrceenLockActivity.this.finish();
				break;
			}
		}
	}

}
